package com.zimu.api.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.nacos.shaded.com.google.gson.reflect.TypeToken;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.zimu.api.mapper.InterfaceInfoMapper;
import com.zimu.api.service.InterfaceInfoService;
import com.zimu.api.service.UserService;
import com.zimu.common.exception.BusinessException;
import com.zimu.common.model.common.ErrorCode;
import com.zimu.common.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import com.zimu.common.model.entity.InterfaceInfo;
import com.zimu.common.model.entity.User;
import com.zimu.common.model.enums.InterfaceInfoMethoedEnum;
import com.zimu.sdk.utils.EncryptUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 何文斌
* @description 针对表【interface_info(接口信息)】的数据库操作Service实现
* @createDate 2024-08-04 17:33:48
*/
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService {
    private static final String GATEWAY_PATH = "http://localhost:8080";
    @Resource
    UserService userService;

    @Override
    public void validInterfaceInfo(InterfaceInfo interfaceInfo, boolean add) {
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
    }

    @Override
    public Object invokeInterface(InterfaceInfoInvokeRequest invokeRequest, HttpServletRequest request) {
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(invokeRequest, interfaceInfo);
        // 参数校验
        this.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = invokeRequest.getId();
        // 判断接口是否存在
        InterfaceInfo oldInterfaceInfo = this.getById(id);
        if (oldInterfaceInfo == null ) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //获取登录用户,填充accessKey和secretKey
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null)
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        Map<String, List<String>> header = null;
        //先判断是get还是post请求
        HttpResponse res = null;
        String requestParams = invokeRequest.getUserRequestParams();
        //GET
        if( InterfaceInfoMethoedEnum.GET.getText().equals(oldInterfaceInfo.getMethod()  ) ){
            if (oldInterfaceInfo.getRequestParams() != null && requestParams == null  )
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            Gson gson = new Gson();
            Map<String,Object> map = null;
            if (StrUtil.isNotBlank(requestParams)){
                map = gson.fromJson(requestParams, new TypeToken<Map<String,Object>>(){}.getType());
            }
            String params = map == null ? "" : map.toString();
            header = geneHeader(params,
                    loginUser.getAccessKey(), loginUser.getSecretKey());
            System.out.println("request.getRequestURL() = " + request.getRequestURL());
            System.out.println("request.getRequestURI() = " + request.getRequestURI());
            res = HttpUtil.createGet(GATEWAY_PATH + oldInterfaceInfo.getUri() )
                    .header(header)
                    .form(map)
                    .execute();
        }else {
            header = geneHeader(invokeRequest.getUserRequestParams(),
                    loginUser.getAccessKey(), loginUser.getSecretKey());
            String body = invokeRequest.getUserRequestParams();
            Gson gson = new Gson();
            User user1 = gson.fromJson(body, User.class);
            System.out.println(user1);
            res = HttpUtil.createPost("http://localhost:8080/name/user")
                    .header(header)
                    .body(body)
                    .execute();
        }
        return res.body();
    }

    private Map<String, List<String>> geneHeader(String json,String accessKey,String secretKey){
        Map<String,List<String>> header = new HashMap<>();
        header.put("accessKey",List.of(accessKey));
        //如果是post，使用body中json+密钥加密,get使用密钥加密
        String encryptKey = EncryptUtil.encrypt(json + secretKey);
        header.put("signed",List.of( encryptKey ));
        //时间戳,不得超过5分钟
        header.put("time",List.of( String.valueOf(System.currentTimeMillis()) ));
        //随机数
        String nonce = String.valueOf(RandomUtil.randomInt(4));
        header.put("nonce", List.of(nonce) );
        return header;
    }
}




